package com.example.administrator.hqq.activity.post;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.util.Util;
import com.example.administrator.hqq.R;
import com.example.administrator.hqq.View.FullyLinearLayoutManager;
import com.example.administrator.hqq.View.ObservableScrollView;
import com.example.administrator.hqq.View.TextVIew;
import com.example.administrator.hqq.View.alertview.AlertViewFactory;
import com.example.administrator.hqq.adapter.discover.PostCommentAdapter;
import com.example.administrator.hqq.adapter.discover.PostDetailsImageListAdapter;
import com.example.administrator.hqq.base.MyActivity;
import com.example.administrator.hqq.bean.Complain;
import com.example.administrator.hqq.bean.ForumComment;
import com.example.administrator.hqq.bean.PostDetailsBean;
import com.example.administrator.hqq.bean.post.PostDetailsCommentBean;
import com.example.administrator.hqq.config.LoongsConfig;
import com.example.administrator.hqq.config.UrlFactory;
import com.example.administrator.hqq.message.PostDetailsMessageEvent;
import com.example.administrator.hqq.utils.BoldTextUtils;
import com.example.administrator.hqq.utils.GetLocationUtils;
import com.example.administrator.hqq.utils.HintWordsUtils;
import com.example.administrator.hqq.utils.MyTextUtils;
import com.example.administrator.hqq.utils.TimeUtils;
import com.example.administrator.hqq.utils.transform.GlideCircleTransform;
import com.example.administrator.hqq.utils.transform.SpacesItemDecoration;
import com.google.gson.Gson;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.GetBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.Conversation;
import okhttp3.Call;

public class PostDetailsActivity extends MyActivity implements ObservableScrollView.OnObservableScrollViewScrollChanged {

    private final String TAG = this.getClass().getSimpleName();
    @BindView(R.id.return_auto)
    AutoRelativeLayout returnAuto;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.post_inform)
    ImageView postInform;
    @BindView(R.id.report_auto)
    AutoRelativeLayout reportAuto;
    @BindView(R.id.search)
    TextView search;
    @BindView(R.id.issue)
    TextView issue;
    @BindView(R.id.user_pic)
    ImageView userPic;
    @BindView(R.id.user_name)
    TextView userName;
    @BindView(R.id.forum_sex)
    ImageView forumSex;
    @BindView(R.id.sex_background)
    AutoRelativeLayout sexBackground;
    @BindView(R.id.same_age)
    TextView sameAge;
    @BindView(R.id.local)
    TextView local;
    @BindView(R.id.chat_button_image)
    ImageView chatButtonImage;
    @BindView(R.id.chat_button_text)
    TextView chatButtonText;
    @BindView(R.id.private_chat)
    AutoLinearLayout privateChat;
    @BindView(R.id.post_title)
    TextView postTitle;
    @BindView(R.id.post_context)
    TextView postContext;
    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.group_image)
    ImageView groupImage;
    @BindView(R.id.group_title)
    TextView groupTitle;
    @BindView(R.id.people_number)
    TextView peopleNumber;
    @BindView(R.id.number_auto)
    AutoLinearLayout numberAuto;
    @BindView(R.id.group_introduce)
    TextView groupIntroduce;
    @BindView(R.id.group_entrance)
    AutoRelativeLayout groupEntrance;
    @BindView(R.id.tv_headerView)
    AutoLinearLayout tvHeaderView;
    @BindView(R.id.post_time)
    TextView postTime;
    @BindView(R.id.comment_number)
    TextView commentNumber;
    @BindView(R.id.post_comment)
    AutoLinearLayout postComment;
    @BindView(R.id.post_praise_image)
    ImageView postPraiseImage;
    @BindView(R.id.praise_number)
    TextView praiseNumber;
    @BindView(R.id.post_praise)
    AutoLinearLayout postPraise;
    @BindView(R.id.tv_topView)
    AutoLinearLayout tvTopView;
    @BindView(R.id.ll_topView)
    AutoLinearLayout llTopView;
    @BindView(R.id.list_view)
    RecyclerView listView;
    @BindView(R.id.ll_contentView)
    AutoLinearLayout llContentView;
    @BindView(R.id.sv_contentView)
    ObservableScrollView svContentView;
    @BindView(R.id.ll_fixedView)
    AutoLinearLayout llFixedView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.collection)
    ImageView collection;
    @BindView(R.id.collection_auto)
    AutoLinearLayout collectionAuto;
    @BindView(R.id.post_details_comment)
    TextView postDetailsComment;
    @BindView(R.id.comment_post)
    AutoLinearLayout commentPost;
    @BindView(R.id.like)
    ImageView like;
    @BindView(R.id.like_auto)
    AutoLinearLayout likeAuto;
    @BindView(R.id.comment_et)
    EditText commentEt;
    @BindView(R.id.issue1)
    AutoLinearLayout issue1;
    @BindView(R.id.auto)
    AutoLinearLayout auto;
    @BindView(R.id.auto_111)
    TextVIew auto111;
    @BindView(R.id.age_number)
    TextView ageNumber;
    @BindView(R.id.age_auto)
    AutoLinearLayout ageAuto;
    @BindView(R.id.location_number)
    TextView locationNumber;
    @BindView(R.id.location_auto)
    AutoLinearLayout locationAuto;

    private int rollPosition = -1;
    private List<PostDetailsCommentBean.DataBean.ReplyBean> listViewData;//评论数据源
    private ArrayAdapter<String> adapter;
    private List<PostDetailsBean.DataBean.PictureUrlBean> data;//数据源
    private PostDetailsImageListAdapter postDetailsImageListAdapter;
    private PostCommentAdapter postCommentAdapter;
    private boolean aBoolean;
    private int page = 1;
    private String last_id;
    private int size = 10;
    private PostDetailsBean postDetailsBean;
    //用来记录内层固定布局到屏幕顶部的距离
    private int mHeight;
    private AlertDialog showReportAlertView;
    private List<String> strings;
    private int removeNum;
    private FullyLinearLayoutManager layoutManager1;
    private Handler handler;
    private Runnable runnable;
    private int recordImageLoaderNumber = 0;
    private String locate_position_id;
    private PostDetailsCommentBean postDetailsCommentBean;
    private int alpht;
    private AutoRelativeLayout viewByPosition;
    private Runnable runnable1;
    private GridLayoutManager gridLayoutManager;
    private GridLayoutManager gridLayoutManager1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_improve_post_details);
        ButterKnife.bind(this);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        locate_position_id = getIntent().getStringExtra(LoongsConfig.locate_position_id);
        if (TextUtils.isEmpty(locate_position_id)) {
            locate_position_id = "";
        }
        initview();
        getPostDetails();
        initData();
        setOnclick();
    }

    private void setOnclick() {
        postCommentAdapter.setOnPostCommentClick(new PostCommentAdapter.OnPostCommentClick() {
            /**
             * 一级评论举报点击事件
             * @param position
             * @param postLick
             */
            @Override
            public void giveLikeOnclick(final int position, final ImageView postLick) {
                replyLike(position, postLick);
                listViewData.get(position).setLike_amount(postLick.isSelected()
                        ? listViewData.get(position).getLike_amount() - 1
                        : listViewData.get(position).getLike_amount() + 1);
                listViewData.get(position).setLike_state(postLick.isSelected() ? 0 : 1);
                postCommentAdapter.notifyDataSetChanged();
            }

            /**
             * 一级评论举报事件
             * @param position1
             */
            @Override
            public void informOnclick(final int position1) {
                strings = new ArrayList<>();
                strings.clear();
                for (String s : PostDetailsActivity.this.getResources().getStringArray(R.array.forum_comment_report)) {
                    strings.add(s);
                }
                showReportAlertView = AlertViewFactory.getInstance().getShowReportAlertView(PostDetailsActivity.this, strings, new AlertViewFactory.ReportOnClickListener() {
                    @Override
                    public void submit(final int position) {
                        Log.e(TAG, "submit: " + position);
                        showReportAlertView.cancel();
                        replyInform(position1, position);
                        listViewData.remove(position1);
                        postCommentAdapter.notifyDataSetChanged();
                    }
                });
            }

            @Override
            public void detailsOnclick(int position) {
                Intent intent = new Intent(PostDetailsActivity.this, CommentDetailsActivity.class);
                intent.putExtra(LoongsConfig.reply_id, listViewData.get(position).getId());
                intent.putExtra(LoongsConfig.forum_id, getIntent().getStringExtra(LoongsConfig.forum_id));
                intent.putExtra(LoongsConfig.position, position);
                intent.putExtra(LoongsConfig.forumPosition, getIntent().getIntExtra(LoongsConfig.forumPosition, 0));
                startActivity(intent);
            }
        });
    }

    /**
     * 一级评论举报
     *
     * @param position1
     * @param position
     */
    private void replyInform(int position1, int position) {
        OkHttpUtils.get().url(UrlFactory.ReportForum())
                .addParams(LoongsConfig.id, listViewData.get(position1).getId())
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.type, "1")
                .addParams(LoongsConfig.reason_id, position + 201 + "")
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "举报评论onError: " + e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "举报评论response: " + response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int code = jsonObject.getInt(LoongsConfig.code);
                    HintWordsUtils.showMarkeWords(jsonObject.getInt(LoongsConfig.code), jsonObject.getString(LoongsConfig.description));
                    if (code == 200) {

                        ToastUtils.showShort("已提交举报");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 一级评论点赞
     *
     * @param position
     * @param postLick
     */
    private void replyLike(int position, ImageView postLick) {
        GetBuilder url = OkHttpUtils.get().url(UrlFactory.getReplyLike());
        url.addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.reply_id, listViewData.get(position).getId())
                .addParams(LoongsConfig.value, postLick.isSelected() ? "0" : "1")
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "一级评论点赞onError: " + e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "一级评论点赞onResponse: " + response);
                JSONObject jsonObject = null;
                try {
                    JSONObject jsonObject1 = new JSONObject(response);
                    int code = jsonObject1.getInt(LoongsConfig.code);
                    if (code == 200) {

                    } else if (code == LoongsConfig.Repeat_report && code == LoongsConfig.mine_forum) {
                        ToastUtils.showShort(jsonObject1.getString(LoongsConfig.description));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private void initview() {
        title.setText(getIntent().getStringExtra(LoongsConfig.name));
        reportAuto.setVisibility(View.VISIBLE);
        FullyLinearLayoutManager layoutManager = new FullyLinearLayoutManager(this);
        gridLayoutManager = new GridLayoutManager(this, 2);
        gridLayoutManager1 = new GridLayoutManager(this, 3);
        //设置帖子详情
        data = new ArrayList<>();
        recycler.setLayoutManager(layoutManager);
        recycler.addItemDecoration(new SpacesItemDecoration(20, 20));
        postDetailsImageListAdapter = new PostDetailsImageListAdapter(this, data);
        recycler.setAdapter(postDetailsImageListAdapter);
        //设置评论
        listViewData = new ArrayList<>();
        postCommentAdapter = new PostCommentAdapter(this, listViewData);
        layoutManager1 = new FullyLinearLayoutManager(this);
        listView.setLayoutManager(layoutManager1);
        listView.setAdapter(postCommentAdapter);
        //设置刷新动画
        refreshLayout.setEnableAutoLoadMore(false);
        refreshLayout.setRefreshHeader(new MaterialHeader(this));
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                //下拉刷新
                size = 10;
                page = 1;
                initData();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                //上拉加载
                size = 10;
                page++;
                initData();
            }
        });
        svContentView.setOnObservableScrollViewScrollChanged(this);
        listView.setHasFixedSize(true);
        listView.setNestedScrollingEnabled(false);
        recycler.setHasFixedSize(true);
        recycler.setNestedScrollingEnabled(false);
        postDetailsImageListAdapter.setPicCountLogic(new PostDetailsImageListAdapter.PicCountLogic() {
            @Override
            public void countLogic() {
                recordImageLoaderNumber += 1;
            }
        });
    }

    /**
     * 获取帖子详情
     */
    public void getPostDetails() {
        OkHttpUtils.get().url(UrlFactory.getForumComtent()).tag(this)
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.forum_id, getIntent().getStringExtra(LoongsConfig.forum_id))
                .addParams(LoongsConfig.city_code, GetLocationUtils.getCityCode())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "获取贴子详情onError: " + e.getMessage());
            }

            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "获取贴子详情onResponse: " + response);
                Gson gson = new Gson();
                postDetailsBean = gson.fromJson(response, PostDetailsBean.class);
                if (postDetailsBean.getCode() == 200) {
                    data.clear();
                    postContext.setText(postDetailsBean.getData().getContent());
                    if (postDetailsBean.getData().getTitle() == null || TextUtils.isEmpty(postDetailsBean.getData().getTitle())) {
                        postTitle.setVisibility(View.GONE);
                    } else {
                        postTitle.setText(postDetailsBean.getData().getTitle());
                    }
                    if (Util.isOnMainThread()) {
                        Glide.with(PostDetailsActivity.this.getApplicationContext())
                                .load(postDetailsBean.getData().getUser_portrait_url())
                                .transform(new CenterCrop(PostDetailsActivity.this.getApplicationContext()), new GlideCircleTransform(PostDetailsActivity.this.getApplicationContext()))
                                .into(userPic);
                    }
                    local.setVisibility(postDetailsBean.getData().getLocation_type() == 0 ? View.GONE : View.VISIBLE);
                    userName.setText(postDetailsBean.getData().getUser_nickname());
                    List<PostDetailsBean.DataBean.PictureUrlBean> picture_url = postDetailsBean.getData().getPicture_url();
                    if (picture_url != null)
                        data.addAll(picture_url);
                    if (data.size()==1)
                    {

                    }else if (data.size()==2||data.size()==4){
                        recycler.setLayoutManager(gridLayoutManager);
                    }else{
                        recycler.setLayoutManager(gridLayoutManager1);
                    }
                    praiseNumber.setText(postDetailsBean.getData().getLike_amount() + "");
                    commentNumber.setText(postDetailsBean.getData().getReply_amount() + "");
                    like.setSelected(postDetailsBean.getData().getLike_state() == 1 ? true : false);
                    collection.setSelected(postDetailsBean.getData().getCollection_state() == 1 ? true : false);

                    postDetailsImageListAdapter.notifyDataSetChanged();
                    postTime.setText(TimeUtils.getTimeStringTwo(postDetailsBean.getData().getTime()));
                    //设置年龄性别属性
                    if (postDetailsBean.getData().getAge_type() == 1) {
                        sameAge.setVisibility(View.VISIBLE);
                    } else {
                        sameAge.setVisibility(View.GONE);
                    }
                    if (postDetailsBean.getData().getGender_type() == 0) {
                        forumSex.setSelected(true);
                        sexBackground.setBackgroundColor(Color.parseColor("#D67FAC"));
                    } else {
                        forumSex.setSelected(false);
                        sexBackground.setBackgroundColor(Color.parseColor("#7F9ED6"));
                    }
                    if (postDetailsBean.getData().getReply_permission() == 0) {
                        commentPost.setSelected(true);
                        postDetailsComment.setTextColor(Color.parseColor("#a19e9e"));
                    }
                    if (postDetailsBean.getData().getChat_permission() == 1) {
                        privateChat.setVisibility(View.VISIBLE);
                        privateChat.setSelected(false);
                        chatButtonImage.setSelected(false);
                        chatButtonText.setText("私聊");
                    }
                    if ("MINE".equals(postDetailsBean.getData().getType())) {
                        postInform.setImageDrawable(getDrawable(R.drawable.dating_delete));
                        privateChat.setVisibility(View.GONE);
                        privateChat.setSelected(true);
                        chatButtonImage.setSelected(true);
                        chatButtonText.setText("删除");
                    }
                    //设置group
                    PostDetailsBean.DataBean.Group group = postDetailsBean.getData().getGroup();
                    if (group != null) {
                        groupEntrance.setVisibility(View.VISIBLE);
                        Glide.with(PostDetailsActivity.this)
                                .load(group.getUrl())
                                .bitmapTransform(new GlideCircleTransform(PostDetailsActivity.this))
                                .into(groupImage);
                        groupTitle.setText(group.getTitle());
                        BoldTextUtils.BoldText(groupTitle);
                        ageNumber.setText(group.getSame_age_count() + "");
                        peopleNumber.setText(group.getMember_amount() + "");
                        locationNumber.setText(group.getSame_city_count() + "");
                        groupIntroduce.setText(group.getIntroduction());
                        if (group.getSame_age_count() == 0) {
                            locationAuto.setVisibility(View.GONE);
                        } else {
                            locationAuto.setVisibility(View.VISIBLE);
                        }
                        if (group.getSame_city_count() == 0) {
                            ageAuto.setVisibility(View.GONE);
                        } else {
                            ageAuto.setVisibility(View.VISIBLE);
                        }
                    }
                }
            }
        });
    }

    public void initData() {
        last_id = "0";
        if (page != 1 && listViewData.size() > 0 && size == 10) {
            last_id = listViewData.get(listViewData.size() - 1).getId();
        }
        //获取评论详情
        OkHttpUtils.get().url(UrlFactory.getForumReply())
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.forum_id, getIntent().getStringExtra(LoongsConfig.forum_id))
                .addParams(LoongsConfig.last_id, last_id)
                .addParams(LoongsConfig.locate_position_id, "")
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "获取评论onError: " + e.getMessage());
                refreshLayout.finishLoadMore();
                refreshLayout.finishRefresh();
                page--;
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "获取评论onResponse: " + response);
                refreshLayout.finishLoadMore();
                refreshLayout.finishRefresh();
                Gson gson = new Gson();
                postDetailsCommentBean = gson.fromJson(response, PostDetailsCommentBean.class);
                if (postDetailsCommentBean.getCode() == 200) {
                    List<PostDetailsCommentBean.DataBean.ReplyBean> reply = postDetailsCommentBean.getData().getReply();
                    removeNum = reply.size();
                    if (page == 1) {
                        listViewData.clear();
                    }
                    listViewData.addAll(reply);
                    postCommentAdapter.notifyDataSetChanged();
                    if (!TextUtils.isEmpty(locate_position_id)) {
                        for (int i = 0; i < listViewData.size(); i++) {
                            if (listViewData.get(i).getId().equals(locate_position_id)) {
                                rollPosition = i;
                                break;
                            }
                        }
                    }
                } else {
                    page--;
                }
            }
        });
        postCommentAdapter.notifyDataSetChanged();

    }

    @OnClick({R.id.return_auto, R.id.comment_post, R.id.collection_auto, R.id.like_auto, R.id.report_auto, R.id.private_chat})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.return_auto:
                finish();
                break;
            case R.id.comment_post:
                //评论
                if (postDetailsBean != null && postDetailsBean.getData() != null && postDetailsBean.getData().getReply_permission() != 0) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                    auto.setVisibility(View.VISIBLE);
                    auto111.setVisibility(View.VISIBLE);
                    auto.setSelected(true);
                    commentEt.setFocusable(true);
                    commentEt.setFocusableInTouchMode(true);
                    commentEt.requestFocus();
                    aBoolean = true;
                }
                break;
            case R.id.collection_auto:
                //收藏
                collection.setSelected(!collection.isSelected());
                collectionForum();
                break;
            case R.id.like_auto:
                //点赞
                likeForum();
                Log.e(TAG, "like.isSelected(): " + like.isSelected());
                break;
            case R.id.report_auto:
                if ("MINE".equals(postDetailsBean.getData().getType())) {
                    AlertDialog.Builder normalDialog =
                            new AlertDialog.Builder(this);
                    normalDialog.setTitle("确定要删除此帖子吗");
                    normalDialog.setPositiveButton("确定",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    deleteForum();
                                }
                            });
                    normalDialog.setNegativeButton("关闭",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    //...To-do
                                }
                            });
                    // 显示
                    normalDialog.show();
                } else {
                    //举报
                    List<String> strings = new ArrayList<>();
                    strings.clear();
                    for (String s : this.getResources().getStringArray(R.array.forum_report)) {
                        strings.add(s);
                    }
                    showReportAlertView = AlertViewFactory.getInstance().getShowReportAlertView(this, strings, new AlertViewFactory.ReportOnClickListener() {
                        @Override
                        public void submit(int position) {
                            Log.e(TAG, "submit: " + position);
                            showReportAlertView.cancel();
                            reportForum(position);
                        }
                    });
                }
                break;
            case R.id.private_chat:
                if (privateChat.isSelected()) {
                    deleteForum();
                } else {
                    addDirectchat();
                }
                break;
        }
    }

    /**
     * 删除贴纸
     */
    private void deleteForum() {
        OkHttpUtils.get().url(UrlFactory.deleterMyforum()).tag(this)
                .addParams(LoongsConfig.user_id, LoongsConfig.getUser_id())
                .addParams(LoongsConfig.forum_id, getIntent().getStringExtra(LoongsConfig.forum_id))
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "贴子删除onError: " + e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "贴子删除onResponse: " + response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int code = jsonObject.getInt(LoongsConfig.code);
                    String description = jsonObject.getString(LoongsConfig.description);
                    if (code == 200) {
                        ForumComment forumComment = new ForumComment(ForumComment.Type.DELETE_FORUM, getIntent().getStringExtra(LoongsConfig.forum_id), 0);
                        EventBus.getDefault().post(forumComment);
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 创建私聊
     */
    private void addDirectchat() {
        if (postDetailsBean != null && postDetailsBean.getData() != null)
            OkHttpUtils.get().url(UrlFactory.addDirectchat())
                    .addParams(LoongsConfig.user_id, LoongsConfig.getUser_id())
                    .addParams(LoongsConfig.other_user_id, postDetailsBean.getData().getOther_user_id())
                    .addParams(LoongsConfig.type, "FORUM")
                    .addParams(LoongsConfig.id, getIntent().getStringExtra(LoongsConfig.forum_id))
                    .build().execute(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    Log.e(TAG, "开启私聊onError: " + e.getMessage());
                }

                @Override
                public void onResponse(String response, int id) {
                    Log.e(TAG, "开启私聊onResponse: " + response);
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        int code = jsonObject.getInt(LoongsConfig.code);
                        String description = jsonObject.getString(LoongsConfig.description);
                        HintWordsUtils.showMarkeWords(code, description);
                        if (code == 200) {
                            LoongsConfig.getUsersIdSPUtils().put(LoongsConfig.Conversation.ConversationID, postDetailsBean.getData().getOther_user_id());
                            SPUtils.getInstance(SPUtils.getInstance().getString(LoongsConfig.user_id)).put(LoongsConfig.Conversation.ChatConversationType, LoongsConfig.Conversation.PRIVATE);
                            RongIM.getInstance().startConversation(PostDetailsActivity.this, Conversation.ConversationType.PRIVATE, postDetailsBean.getData().getOther_user_id(), "");
                            Complain complain = new Complain(Complain.Type.DIRECTCHAT, "");
                            EventBus.getDefault().post(complain);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
    }

    /**
     * 收藏贴子
     */
    private void collectionForum() {
        OkHttpUtils.get().url(UrlFactory.getForumCollect())
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.forum_id, getIntent().getStringExtra(LoongsConfig.forum_id))
                .addParams(LoongsConfig.value, collection.isSelected() ? "1" : "0")
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "收藏onError: " + e);
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "收藏onResponse: " + response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getInt(LoongsConfig.code) == 200) {

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 点赞贴子
     */
    private void likeForum() {
        like.setSelected(!like.isSelected());
        if (postDetailsBean != null) {
            postDetailsBean.getData().setLike_amount(like.isSelected() ? postDetailsBean.getData().getLike_amount() + 1 : postDetailsBean.getData().getLike_amount() - 1);
            praiseNumber.setText(postDetailsBean.getData().getLike_amount() + "");
        }
        GetBuilder url = OkHttpUtils.get().url(UrlFactory.getForumlike());
        url.addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.forum_id, getIntent().getStringExtra(LoongsConfig.forum_id))
                .addParams(LoongsConfig.value, like.isSelected() ? "1" : "0")
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "评论详情点赞onError: " + e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "onResponse: " + response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getInt(LoongsConfig.code) == 200) {
                        EventBus.getDefault().post(new PostDetailsMessageEvent("0", like.isSelected()));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 举报帖子
     *
     * @param position
     */
    private void reportForum(int position) {
        OkHttpUtils.get().url(UrlFactory.ReportForum())
                .addParams(LoongsConfig.id, getIntent().getStringExtra(LoongsConfig.forum_id))
                .addParams(LoongsConfig.type, "0")
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.reason_id, position + 101 + "")
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "举报帖子onError: " + e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "举报帖子response: " + response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int code = jsonObject.getInt(LoongsConfig.code);
                    HintWordsUtils.showMarkeWords(jsonObject.getInt(LoongsConfig.code), jsonObject.getString(LoongsConfig.description));
                    if (code == 200) {
                        ToastUtils.showShort("已提交举报");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        ForumComment forumComment = new ForumComment(ForumComment.Type.FORUM_REPORT, getIntent().getStringExtra(LoongsConfig.forum_id), -1);
        EventBus.getDefault().post(forumComment);
        finish();
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            if (aBoolean && isShouldHideKeyboard(auto, ev) && !isShouldHideKeyboard(auto111, ev)) {
                if (isSoftShowing()) {
                    final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                }
                auto.setVisibility(View.GONE);
                auto111.setVisibility(View.GONE);
                auto.setSelected(false);
                Log.e(TAG, "jinaaa: ");
                boolean a = aBoolean;
                aBoolean = false;
                return a;
            } else if (!isShouldHideKeyboard(commentEt, ev)) {
                if (auto.isSelected()) {
                    if (!isSoftShowing()) {
                        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }
            } else if (!isShouldHideKeyboard(issue1, ev)) {
                replyPost();
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 评论处理函数
     */
    private void replyPost() {
        String s = commentEt.getText().toString();
        if (MyTextUtils.isEmptyString(commentEt)) {
            ToastUtils.showShort("不能发出全是空格的内容");
            return;
        }
        showLoadingDialog();
        if (!TextUtils.isEmpty(s))
            OkHttpUtils.get().url(UrlFactory.reolyForum())
                    .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                    .addParams(LoongsConfig.forum_id, getIntent().getStringExtra(LoongsConfig.forum_id))
                    .addParams(LoongsConfig.text, s)
                    .build().execute(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    Log.e(TAG, "发表评论onError: " + e.getMessage());
                    dismissLoadingDialog();
                }

                @Override
                public void onResponse(String response, int id) {
                    Log.e(TAG, "发表评论onResponse: " + response);
                    dismissLoadingDialog();
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (jsonObject.getInt(LoongsConfig.code) == 200) {
                            //type==2表示发布一条新评论更新帖子列表的评论数量
                            PostDetailsMessageEvent postDetailsMessageEvent = new PostDetailsMessageEvent("2", like.isSelected());
                            postDetailsMessageEvent.setForumPosition(getIntent().getIntExtra(LoongsConfig.forumPosition, 0));
                            EventBus.getDefault().post(postDetailsMessageEvent);

                            commentEt.setText("");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        auto.setVisibility(View.GONE);
        auto111.setVisibility(View.GONE);
        auto.setSelected(false);
        if (isSoftShowing()) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 判断输入框是否显示
     *
     * @return
     */
    private boolean isSoftShowing() {
        //获取当前屏幕内容的高度
        int screenHeight = getWindow().getDecorView().getHeight();
        //获取View可见区域的bottom
        Rect rect = new Rect();
        getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        return screenHeight - rect.bottom - getSoftButtonsBarHeight() != 0;
    }

    /**
     * 底部虚拟按键栏的高度
     *
     * @return
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    private int getSoftButtonsBarHeight() {
        DisplayMetrics metrics = new DisplayMetrics();
        //这个方法获取可能不是真实屏幕的高度
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int usableHeight = metrics.heightPixels;
        //获取当前屏幕的真实高度
        getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
        int realHeight = metrics.heightPixels;
        if (realHeight > usableHeight) {
            return realHeight - usableHeight;
        } else {
            return 0;
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            //获取HeaderView的高度，当滑动大于等于这个高度的时候，需要把topView移除当前布局，放入到外层布局
            mHeight = tvHeaderView.getMeasuredHeight();
        }
    }

    @SuppressLint("NewApi")
    @Override
    protected void onResume() {
        super.onResume();
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
        final int realHeight = metrics.heightPixels;
        if (handler == null) {
            handler = new Handler();
        }
        if (runnable == null) {
            runnable = new Runnable() {
                @Override
                public void run() {
                    if (postDetailsBean != null && recordImageLoaderNumber >= postDetailsBean.getData().getPicture_url().size() && postDetailsCommentBean != null && rollPosition >= 0) {
                        Log.e(TAG, "run: size     " + postDetailsBean.getData().getPicture_url().size() + "recordImageLoaderNumber:     " + recordImageLoaderNumber);
                        viewByPosition = (AutoRelativeLayout) layoutManager1.findViewByPosition(rollPosition);
                        if (viewByPosition == null) {
                            handler.postDelayed(runnable, 500);
                        } else {
                            //仿微博的颜色渐变
                            alpht = 255;
                            runnable1 = new Runnable() {
                                @Override
                                public void run() {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            viewByPosition.setBackgroundColor(Color.argb(alpht, 127, 214, 206));
                                        }
                                    });
                                    alpht = alpht - 5;
                                    if (alpht != 0) {
                                        handler.postDelayed(runnable1, 20);
                                    }
                                }
                            };
                            handler.postDelayed(runnable1, 20);
                            int[] screenLocation = new int[2];
                            int measuredHeight = viewByPosition.getMeasuredHeight();
                            viewByPosition.getLocationOnScreen(screenLocation);
                            svContentView.smoothScrollTo(0, screenLocation[1] - realHeight / 2 + measuredHeight / 2);
                            locate_position_id = "";
                            Log.e(TAG, "onWindowFocusChanged: x   " + screenLocation[0] + "   Y :    " + screenLocation[1]);
                        }
                    } else {
                        handler.postDelayed(runnable, 500);
                    }
                }
            };
        }
        if (!TextUtils.isEmpty(locate_position_id)) {
            handler.postDelayed(runnable, 500);
        }
    }

    /**
     * @param l    Current horizontal scroll origin. 当前滑动的x轴距离
     * @param t    Current vertical scroll origin. 当前滑动的y轴距离
     * @param oldl Previous horizontal scroll origin. 上一次滑动的x轴距离
     * @param oldt Previous vertical scroll origin. 上一次滑动的y轴距离
     */
    @Override
    public void onObservableScrollViewScrollChanged(int l, int t, int oldl, int oldt) {
        Log.e(TAG, "getHeight: " + tvHeaderView.getMeasuredHeight());
        if (t >= tvHeaderView.getMeasuredHeight()) {
            if (tvTopView.getParent() != llFixedView) {
                llTopView.removeView(tvTopView);
                llFixedView.addView(tvTopView);
            }
        } else {
            if (tvTopView.getParent() != llTopView) {
                llFixedView.removeView(tvTopView);
                llTopView.addView(tvTopView);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(PostDetailsMessageEvent postDetailsMessageEvent) {
        if ("2".equals(postDetailsMessageEvent.getType())) {
            page = 1;
            initData();
            getPostDetails();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(ForumComment messageEvent) {
        //当评论详情操作数据时更新本页面的ui
        int position = messageEvent.getPosition();
        if (messageEvent != null && messageEvent.getType() != null && messageEvent.getPosition() != -1) {
            PostDetailsCommentBean.DataBean.ReplyBean replyBean = listViewData.get(position);
            switch (messageEvent.getType()) {
                case REPLY_REPORT:
                    listViewData.remove(position);
                    break;
                case REPLY_LIKE:
                    replyBean.setLike_state(messageEvent.isLike() ? 1 : 0);
                    replyBean.setLike_amount(messageEvent.isLike()
                            ? listViewData.get(position).getLike_amount() + 1
                            : listViewData.get(position).getLike_amount() - 1);
                    break;
                case DISCUSSION_REPORT:
                    for (int i = 0; i < replyBean.getDiscussion().size(); i++) {
                        if (replyBean.getDiscussion().get(i).equals(messageEvent.getId())) {
                            replyBean.getDiscussion().remove(i);
                            break;
                        }
                    }
                    break;
                case ADD_DISCUSSION:
                    PostDetailsCommentBean.DataBean.ReplyBean.Discussion discussion = new PostDetailsCommentBean.DataBean.ReplyBean.Discussion();
                    discussion.setId(messageEvent.getUserID());
                    discussion.setText(messageEvent.getCommentContext());
                    discussion.setUser_nickname("试试喜欢喜");
                    replyBean.getDiscussion().add(0, discussion);
                    break;
            }
            postCommentAdapter.notifyDataSetChanged();
            listView.scrollToPosition(position);
            LinearLayoutManager mLayoutManager = (LinearLayoutManager) listView.getLayoutManager();
            mLayoutManager.scrollToPositionWithOffset(position, 0);
        }
    }

    @Override
    protected String getActivityName() {
        return this.getClass().getSimpleName();
    }
}